package com.mojawa.mj_util.permiss

import android.Manifest
import android.app.Activity
import android.content.pm.PackageManager
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat

object PermissionUtils {

    fun checkLocationPermission(activity: Activity, onPermissionGranted: () -> Unit) {
        val context = this ?: return  // 确保 context 不为 null
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(activity, Manifest.permission.FOREGROUND_SERVICE_LOCATION) == PackageManager.PERMISSION_GRANTED
        ) {
            Log.i("Permission", "权限已全部授予，立即执行操作")
            onPermissionGranted()  // 执行回调
        } else {
            Log.i("Permission", "请求权限")
            onPermissionGrantedAction = onPermissionGranted  // 保存回调
            ActivityCompat.requestPermissions(
                activity,
                arrayOf(
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.FOREGROUND_SERVICE_LOCATION
                ),
                LOCATION_PERMISSION_REQUEST_CODE
            )
        }
    }

    fun handlePermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
        activity: Activity
    ) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                Log.i("Permission", "权限已授予")
                onPermissionGrantedAction?.invoke()
            } else {

                Log.i("Permission", "权限被拒绝")
                Toast.makeText(activity, "需要授予权限才能继续操作", Toast.LENGTH_SHORT).show()
                // 停止前台服务
//                MJTimeUtil.closeServiceCompat(activity,Intent(activity, MJAMapLocationService::class.java))
            }
        }
    }
    val LOCATION_PERMISSION_REQUEST_CODE = 1000
    var onPermissionGrantedAction: (() -> Unit)? = null
}